package com.syqc.utils

import android.content.Context
import android.util.LruCache
import com.amap.api.maps.model.BitmapDescriptor
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.syqc.maps.utils.MarkerSet.mMarkerSet
import com.syqc.maps.clusters.MarkerView

/** @author joker @date 2022/9/2$ 10:50$ */
object MarkerBitmapUtil {

    fun getBitmapDes(
        context: Context,
        carId: String,
        state: String,
        drct: String,
        carName: String,
        carPlate: String,
        iconLink: String,
        isPlate: Boolean,
        speed: String
    ): BitmapDescriptor {
        if (mLogoCache == null) initLruCache()
        var bitmapDescriptor: BitmapDescriptor?
        val key = iconLink + carId + drct + isPlate + speed + mMarkerSet.showSpeed
        bitmapDescriptor = mLogoCache!!.get(key)
        if (bitmapDescriptor == null) {
            val markerView = MarkerView(context, mMarkerSet)
            if (isPlate) {
                markerView.setMarkerInfo(carPlate, iconLink, state, drct, speed)
            } else {
                markerView.setMarkerInfo(carName, iconLink, state, drct, speed)
            }
            bitmapDescriptor = BitmapDescriptorFactory.fromView(markerView)
            mLogoCache!!.put(key, bitmapDescriptor)
        }
        return bitmapDescriptor!!
    }

    private var mLogoCache: LruCache<String, BitmapDescriptor>? = null
    private fun initLruCache() {
        if (mLogoCache == null) {
            mLogoCache = object : LruCache<String, BitmapDescriptor>(80) {
                override fun entryRemoved(
                    evicted: Boolean, key: String?,
                    oldValue: BitmapDescriptor?, newValue: BitmapDescriptor?
                ) {
                    super.entryRemoved(evicted, key, oldValue, newValue)
                    oldValue?.recycle()
                }
            }
        }
    }

    fun recycleLruCache() {
        if (mLogoCache != null) {
            mLogoCache!!.evictAll()
            mLogoCache = null
        }
    }
}